<?php
namespace Wap\Model;
use Think\Model;

class VoteModel extends Model//TODO: 代码优化
{
	protected $tableName = "praise_record2";

	public function insert( $datas )
	{
		$result = array( "success"	=>	false,	"data"	=>	array() );

		$this->startTrans();
		$id = $this->data( $datas )->add();//增加一条点赞记录

		$show = D( "show" );
		$updated_votes = $show->update_votes( $datas['pid'] );//更新本作品的票数、排名、票数差

		if( $id && $updated_votes ){
			$this->commit();
			$result['success'] = true;
			$result['data'] = $show->fetch_rank_by_id( $datas['pid'] );
		}else{
			$this->rollback();
		}

		return $result;
	}

	public function fetch_openid_votes( $openid = "", $praise, $begin_time = 0, $end_time = 0 )
	{
		$count	=	0;

		if( $end_time - $begin_time > 0 ){
			$count	=	$this->where( "openid = '%s' AND praise = %d AND updated_time > %d AND updated_time < %d", array( $openid, $praise, $begin_time, $end_time ) )
				->count();	
		}else if( $end_time - $begin_time < 0 && $end_time == 0 ){
			$count	=	$this->where( "openid = '%s' AND praise = %d AND updated_time > %d", array( $openid, $praise, $begin_time ) )
				->count();
		}

		return $count;
	}

	public function fetch_pid_votes( $openid = "", $pid = "", $begin_time = 0, $end_time = 0 )
	{
		$count = 0;

		if( $end_time - $begin_time > 0 ){
			$count	=	$this->where( "openid = '%s' AND pid = '%d' AND updated_time > %d AND updated_time < %d", array( $openid, $pid, $begin_time, $end_time ) )
				->count();
		}else if( $end_time - $begin_time < 0 && $begin_time == 0 ){
			$count	=	$this->where( "openid = '%s' AND pid = '%d' AND updated_time > %d", array( $openid, $pid, $begin_time ) )
				->count();
		}

		return $count;
		//$updated_rank  = $show->update_rank( $datas['pid'] );//更新上个作品的排名、票数差
	}
}
?>
